package com.skivingcloud.admin.sys.service.impl;

import com.skivingcloud.admin.sys.entity.SysRole;
import com.skivingcloud.admin.sys.entity.SysRoleMenu;
import com.skivingcloud.admin.sys.entity.SysUserRole;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.mapper.SysRoleMapper;
import com.skivingcloud.admin.sys.mapper.SysRoleMenuMapper;
import com.skivingcloud.admin.sys.mapper.SysUserRoleMapper;
import com.skivingcloud.admin.sys.service.ISysRoleService;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.StringUtils;
import com.skivingcloud.common.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONObject;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-29
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
	@Autowired
	private SysRoleMapper sysRoleMapper;
	@Autowired
	private SysRoleMenuMapper sysRoleMenuMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	/**
	 * 分页查询
	 * 
	 * @param params 参数
	 * @param user   操作用户
	 * @return
	 */
	public PageUtils queryPage(Map<String, Object> params, User user) {
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<Object> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		JSONObject parObj = JSONObject.fromObject(params.get("dataForm"));
		Map<String, Object> paramsNew = new HashMap<String, Object>();
		if (parObj.get("roleName") != null && !"".equals(parObj.get("roleName"))) {
			paramsNew.put("roleName", "%" + parObj.get("roleName").toString() + "%");
		}
		if (parObj.get("tenantName") != null && !"".equals(parObj.get("tenantName"))) {
			paramsNew.put("tenantName", "%" + parObj.get("tenantName").toString() + "%");
		}
		if (!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			paramsNew.put("tenantId", user.getTenantId());
		}
		sysRoleMapper.selectByParams(paramsNew);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}

	@Transactional(rollbackFor = Exception.class)
	public void saveMe(SysRole role) {
		LocalDateTime date = LocalDateTime.now();
		role.setCreateTime(date);
		// this.insert(role);

		// 检查权限是否越权
		checkPrems(role);

		// 保存角色与菜单关系
		// sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
	}

	@Transactional(rollbackFor = Exception.class)
	public void update(SysRole role) {
		// this.updateById(role);

		// 检查权限是否越权
		checkPrems(role);

		// 更新角色与菜单关系
		// sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
	}

	@Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] roleIds) throws Exception {
		for (String roleId : roleIds) {
			// 删除角色
			sysRoleMapper.deleteById(roleId);

			QueryWrapper<SysRoleMenu> queryWrapperRM = new QueryWrapper<SysRoleMenu>();
			queryWrapperRM.eq("role_id", roleId);
			// 删除角色与菜单关联
			sysRoleMenuMapper.delete(queryWrapperRM);

			// 删除角色与用户关联
			QueryWrapper<SysUserRole> queryWrapperUR = new QueryWrapper<SysUserRole>();
			queryWrapperUR.eq("role_id", roleId);
			sysUserRoleMapper.delete(queryWrapperUR);
		}

	}

	public List<Long> queryRoleIdList(Long createUserId) {
		return null;// baseMapper.queryRoleIdList(createUserId);
	}

	/**
	 * 检查权限是否越权
	 */
	private void checkPrems(SysRole role) {
		// 如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
		// if(role.getCreateUserId() == Constant.SUPER_ADMIN){
		// return ;
		// }

		// 查询用户所拥有的菜单列表
		// List<Long> menuIdList =
		// sysUserService.queryAllMenuId(role.getCreateUserId());

		// 判断是否越权
		// if(!menuIdList.containsAll(role.getMenuIdList())){
		//// throw new RRException("新增角色的权限，已超出你的权限范围");
		// }
	}

	@Override
	public List<SysRoleMenu> getResTreeByRoleId(String id) {
		QueryWrapper<SysRoleMenu> queryWrapperRM = new QueryWrapper<SysRoleMenu>();
		queryWrapperRM.eq("role_id", id);
		return sysRoleMenuMapper.selectList(queryWrapperRM);
	}

	@Override
	public SysRole selectById(String roleId) {
		return sysRoleMapper.selectById(roleId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void save(SysRole role, User user) throws Exception {
		LocalDateTime date = LocalDateTime.now();
		role.setId(UuidUtil.get32UUID());
		role.setCreateUserId(user.getId());
		role.setCreateTime(date);
		role.setModTime(date);
		role.setModUserId(user.getId());
		if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			// 超级管理员（租户）用户可以设置角色的租户
			if (StringUtils.isBlank(role.getTenantId())) {
				throw new BusinessException("终端id不允许为空");
			}
		} else {
			// 非超级管理员（租户）用户直接将租户设置为自己的租户，即各租户只能增加自己的角色
			role.setTenantId(user.getTenantId());
		}
		sysRoleMapper.insert(role);
		for (String resid : role.getResId()) {
			SysRoleMenu rm = new SysRoleMenu();
			rm.setId(UuidUtil.get32UUID());
			rm.setMenuId(resid);
			rm.setRoleId(role.getId());
			sysRoleMenuMapper.insert(rm);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void update(SysRole role, User user) throws Exception {
		LocalDateTime date = LocalDateTime.now();
		role.setModTime(date);
		role.setModUserId(user.getId());
		sysRoleMapper.updateById(role);
		// 先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
		if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			QueryWrapper<SysRoleMenu> queryWrapperRM = new QueryWrapper<SysRoleMenu>();
			queryWrapperRM.eq("role_id", role.getId());
			// 删除角色与菜单关联
			sysRoleMenuMapper.delete(queryWrapperRM);

		} else {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("roleId", role.getId());
			param.put("tenantId", user.getTenantId());
			sysRoleMenuMapper.deleteByStationIdAndTenantId(param);
		}
		for (String resid : role.getResId()) {
			SysRoleMenu rm = new SysRoleMenu();
			rm.setId(UuidUtil.get32UUID());
			rm.setMenuId(resid);
			rm.setRoleId(role.getId());
			sysRoleMenuMapper.insert(rm);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void setRoleMenu(SysRole role, User user) {
		// 先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
		if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			QueryWrapper<SysRoleMenu> queryWrapperRM = new QueryWrapper<SysRoleMenu>();
			queryWrapperRM.eq("role_id", role.getId());
			// 删除角色与菜单关联
			sysRoleMenuMapper.delete(queryWrapperRM);
		} else {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("roleId", role.getId());
			param.put("tenantId", user.getTenantId());
			sysRoleMenuMapper.deleteByStationIdAndTenantId(param);
		}
		for (String resid : role.getResId()) {
			SysRoleMenu rm = new SysRoleMenu();
			rm.setId(UuidUtil.get32UUID());
			rm.setMenuId(resid);
			rm.setRoleId(role.getId());
			sysRoleMenuMapper.insert(rm);
		}
	}

	@Override
	public PageUtils queryUserRoleList(Map<String, Object> params) {
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		String roleId = params.get("roleId") == null ? "" : params.get("roleId").toString();
		List<Map<String, Object>> list = sysUserRoleMapper.selectByRoleId(roleId);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}

	/**
	 * 获取有效用户，不包含员工及已添加的用户，只能选择当前角色租户下的用户
	 * 
	 * @param params
	 * @return
	 */
	@Override
	public PageUtils queryUserRoleNoChooseList(Map<String, Object> params, User user) {
		String roleId = params.get("roleId") == null ? "" : params.get("roleId").toString();
		SysRole role = sysRoleMapper.selectById(roleId);// 这个放在前面，否则分页有问题
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		JSONObject dataForm = JSONObject.fromObject(params.get("dataForm"));
		String staffName = null;
		String orgName = null;
		if (dataForm != null && StringUtils.isNotBlank(dataForm.get("staffName"))) {
			staffName = "%" + dataForm.getString("staffName") + "%";
		}
		if (dataForm != null && StringUtils.isNotBlank(dataForm.get("orgName"))) {
			orgName = "%" + dataForm.getString("orgName") + "%";
		}
		Map<String, String> queryPra = new HashMap<String, String>();
		queryPra.put("tenantId", role.getTenantId());
		queryPra.put("roleId", roleId);
		queryPra.put("staffName", staffName);
		queryPra.put("orgName", orgName);
		queryPra.put("status", Constant.USER_STATUS_NORMAL);
		List<Map<String, Object>> list = sysUserRoleMapper.selectByRoleIdNoChoose(queryPra);
		pageUtils.setList(list);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void setSysRoleUser(String userId, String roleId, User user) {
		SysUserRole record = new SysUserRole();
		record.setId(UuidUtil.get32UUID());
		record.setRoleId(roleId);
		record.setUserId(userId);
		sysUserRoleMapper.insert(record);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteSysRoleUser(String id, User user) {
		sysUserRoleMapper.deleteById(id);
	}

}
